package com.tcdp.daos;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.tcdp.models.BlogPost;

public class BlogDao extends AbstractDao {

	public BlogPost findByKey(int id){
		BlogPost blogPost = em.find(BlogPost.class, id);
		return blogPost;
	}
	
	public BlogPost findByUrl(String url){
		BlogPost blogPost = null;
		
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<BlogPost> cq = cb.createQuery(BlogPost.class);
		Root<BlogPost> root = cq.from(BlogPost.class);
		cq.select(root).where(cb.equal(root.<String>get("blogPostUrl"), url));
		TypedQuery<BlogPost> tq = em.createQuery(cq);
		try{
			
			blogPost = tq.getSingleResult();
		}catch(NoResultException e){
			throw404(e);
		}
		
		return blogPost;
	}
	
	public List<BlogPost> retrieveAllBlogs(){
		List<BlogPost> blogPosts = null;
		
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<BlogPost> cq = cb.createQuery(BlogPost.class);
		Root<BlogPost> root = cq.from(BlogPost.class);
		cq.select(root);
		TypedQuery<BlogPost> tq = em.createQuery(cq);
		blogPosts = tq.getResultList();
		
		return blogPosts;
	}
	
	public List<BlogPost> retrieveBlogsByCategoryId(int id){
		List<BlogPost> blogPosts = null;
		
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<BlogPost> cq = cb.createQuery(BlogPost.class);
		Root<BlogPost> root = cq.from(BlogPost.class);
		cq.select(root).where(cb.equal(root.get("blogCategoryId"), id));
		TypedQuery<BlogPost> tq = em.createQuery(cq);
		blogPosts = tq.getResultList();
		
		return blogPosts;
	}
	
}
